from PIL import Image, ImageDraw, ImageFont
import cv2
import numpy as np

def pic_text_CN(image, text, point, fillColor, size=20):
    image_cv2 = image.copy()
    setFont = ImageFont.truetype('core/utils/ali.ttf',size, encoding='utf-8')
    # 转换为PIL.Image
    image = Image.fromarray(image_cv2)
    # 新建绘图句柄
    draw = ImageDraw.Draw(image)
    # 得到text的box大小
    x1,y1,x2,y2 = draw.textbbox(point,text, setFont)
    width = (x2-x1)
    height = (y2-y1)
    y1 -= size//4
    # 绘制背景

    image_cv2 = cv2.rectangle(image_cv2, [x1 - 1 , y1 - 1 - height - height//4], [x1+width, y1-1], fillColor, -1)
    image = Image.fromarray(image_cv2)
    draw = ImageDraw.Draw(image)
    # 写字
    draw.text([x1,y1-height-height//2], text, font=setFont, fill=(255,255,255), direction=None)
    # 重新转回cv2.array
    image_ret = np.asarray(image)
    return image_ret

def pic_text(image, text, point, fillColor, size=20):
    draw_thickness = min(image.shape[:2]) // 320
    [xmin, ymin] = point
    (tw,th),_ = cv2.getTextSize(text,cv2.FONT_HERSHEY_COMPLEX_SMALL,1,draw_thickness)
    pts = np.array([[xmin + 1, ymin - th],[xmin + 1 + tw, ymin - th],  [xmin + tw + 1, ymin], [xmin + 1, ymin]],dtype=np.int32)
    image = cv2.fillPoly(image,[pts],color=fillColor)
    image = cv2.putText(image,text,(xmin + 1, ymin),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,255,255))
    return image
        

if __name__=="__main__":

    size=None
    #gen_img()
        
    #** ImageFont模块**
    #选择文字字体和大小
    #设置文字颜色
    text="兔子等着瞧"
    size=(40,40)
    filepath="data/input/DJI_20230203163133_0013_W.JPG"

    #打开图片
    image=cv2.imread(filepath)
    #添加文字
    image = pic_text(image,text,(100,100),fillColor = (0,0,0), size = 20)
    cv2.imwrite("data/output/temp.jpg",image)